package com.geteway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: microservices
 * @ClassName PrintLogGatewayFilterFactory
 * @description:
 * @author: slfang
 * @create: 2024-01-03 16:22
 * @Version 1.0
 **/
@Component
@Slf4j
public class PrintLogGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        // 放到这里应用启动的时候会执行两次次，这是一个坑，需要放到方法里面
        //   log.info("打印请求信息:{}:{}",config.getName(),config.getValue());
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("打印请求信息:{}:{}",config.getName(),config.getValue());
                // 获取request就可以进行修改了
                // 设置请求值
                ServerHttpRequest modifiedRequest = exchange.getRequest().mutate()
                        .header(config.getName(), config.getValue()).build();
                ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();
                return chain.filter(modifiedExchange);
            }
        };
}

    @Override
    public ShortcutType shortcutType() {
        return super.shortcutType();
    }
}
